#!/usr/bin/env python2.4
__license__ = "GNU Lesser General Public License, Ver.2"
__author__ = "Grigory Bakunov <bobuk@justos.org>"

import os
import sys
from config import *

class User:
    def __init__(self, name):
        self.name = name
        self.dirpath = os.path.join(authPath, name)
        self.setup()

    def isRegistered(self):
        return os.path.isdir(self.dirpath)

    def setup(self):
        self.password = None
        self.info     = {}
        if self.isRegistered():
            _upass = os.path.join(self.dirpath, 'password')
            if os.path.isfile(_upass):
                self.password = open(_upass).read()
            _uinfo = os.path.join(self.dirpath, 'info')
            if os.path.isfile(_uinfo):
                self.info = open(_uinfo).readlines()
        return

    def getseq(self, passwd):
        import md5
        return md5.new('%s:%s' % (self.name, passwd)).hexdigest()

    def checkseq(self, seq):
        return self.isRegistered() and seq == self.password

    def checkpass(self, passwd):
        return self.isRegistered() and self.getseq(passwd) == self.password

    def setpass(self, passwd):
        self.password = self.getseq(passwd)

    def delete(self):
        if os.path.isdir(self.dirpath):
            try:
                _upass = os.path.join(self.dirpath, 'password')
                _uinfo = os.path.join(self.dirpath, 'info')
                os.remove(_upass)
                os.remove(_uinfo)
            except:
                pass
            os.rmdir(self.dirpath)
        return

    def save(self):
        try:
            os.makedirs(self.dirpath)
        except:
            pass
        _upass = os.path.join(self.dirpath, 'password')
        _uinfo = os.path.join(self.dirpath, 'info')
        if self.password != None:
            _fl = open(_upass, 'w')
            _fl.write(self.password)
            _fl.close()
        _fl = open(_uinfo, 'w')
        _fl.writelines(self.info)
        _fl.close()

def getUsersList():
    return os.listdir(authPath)

def getAccess(ck, area = None):
    try:
	if User(ck.wmUser).checkseq(ck.wmSeq):
	    user = ck.wmUser
	    edit = True
	else:
            raise Exception('Wrong user')
    except: 
	user=None
	edit=False
    return (user, edit)


def __test__( ps = 0):
    if ps == 0:
        tp = User('bobuk')
        tp.setpass('marspolaris')
        tp.save()
    elif ps == 1:
        tp = User('bobuk')
        print tp.checkpass('marspolaris')
